import math

def out_of_china(lat, lon):
    return not (72.004 <= lon <= 137.8347 and 0.8293 <= lat <= 55.8271)

def wgs84_to_gcj02(lat, lon):
    if out_of_china(lat, lon):
        return lat, lon

    a = 6378245.0
    ee = 0.00669342162296594323

    dlat = transform_lat(lon - 105.0, lat - 35.0)
    dlon = transform_lon(lon - 105.0, lat - 35.0)

    radlat = lat / 180.0 * math.pi
    magic = math.sin(radlat)
    magic = 1 - ee * magic * magic
    sqrtmagic = math.sqrt(magic)

    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * math.pi)
    dlon = (dlon * 180.0) / (a / sqrtmagic * math.cos(radlat) * math.pi)

    mg_lat = lat + dlat
    mg_lon = lon + dlon

    return mg_lat, mg_lon

def transform_lat(x, y):
    ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x))
    ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(y * math.pi) + 40.0 * math.sin(y / 3.0 * math.pi)) * 2.0 / 3.0
    ret += (160.0 * math.sin(y / 12.0 * math.pi) + 320.0 * math.sin(y * math.pi / 30.0)) * 2.0 / 3.0
    return ret

def transform_lon(x, y):
    ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x))
    ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(x * math.pi) + 40.0 * math.sin(x / 3.0 * math.pi)) * 2.0 / 3.0
    ret += (150.0 * math.sin(x / 12.0 * math.pi) + 300.0 * math.sin(x / 30.0 * math.pi)) * 2.0 / 3.0
    return ret

def gcj02_to_wgs84(lat, lon):
    if out_of_china(lat, lon):
        return lat, lon
    
    # 初始值
    delta = 0.01  # 偏差
    lat_diff = delta
    lon_diff = delta
    wgs_lat = lat - lat_diff
    wgs_lon = lon - lon_diff

    # 迭代计算
    for _ in range(10):  # 迭代次数
        mg_lat, mg_lon = wgs84_to_gcj02(wgs_lat, wgs_lon)
        lat_diff = lat - mg_lat
        lon_diff = lon - mg_lon
        wgs_lat += lat_diff
        wgs_lon += lon_diff

    return wgs_lat, wgs_lon

# 示例 GCJ-02 坐标
gcj_lat = 21.679310  # 示例 GCJ-02 纬度
gcj_lon = 110.919433  # 示例 GCJ-02 经度

# 转换 GCJ-02 到 WGS-84
wgs_lat, wgs_lon = gcj02_to_wgs84(gcj_lat, gcj_lon)
print(f"GCJ-02 转 WGS-84: 纬度 {wgs_lat}, 经度 {wgs_lon}")
